<?php
/**
 * Author:   tangxiaowen
 * Email:    846506584@qq.com
 * Date:     2021/3/3 0003 14:57
 * Describe: 企业微信服务 - token相关类
 */

namespace app\common\server\corp;

use think\exception\ValidateException;
use app\common\model\corp\Corp;

class Token extends Base
{
    /**
     * 数据缓存时间/秒
     * @var int
     */
    private $cacheTime = 7000;

    /**
     * @var string 获取待授权方企业微信的accessToken Url
     */
    private $getAuthCorpAccessTokenUrl = 'https://qyapi.weixin.qq.com/cgi-bin/service/get_corp_token?suite_access_token=%s';

    /**
     * @var string 获取SuiteAccessToken Url
     */
    private $getSuiteAccessTokenUrl = 'https://qyapi.weixin.qq.com/cgi-bin/service/get_suite_token';

    /**
     * 获取待授权方企业微信的accessToken
     * @throws ValidateException
     * @return string
     */
    public function getAuthCorpAccessToken(string $corpId): string
    {
        $authCorpAccessToken = cache($corpId . 'authCorpAccessToken');
        if(!$authCorpAccessToken){
            $authCorpInfo = Corp::where('corpid', $corpId)->field('corpid,permanent_code')->find();
            $res = $this->curlFn(sprintf($this->getAuthCorpAccessTokenUrl, $this->getSuiteAccessToken()), [
                'auth_corpid' => $corpId,
                'permanent_code' => $authCorpInfo['permanent_code'],
            ]);
            $temp = $this->setResponse($res);
            if(isset($temp['access_token'])){
                cache($corpId . 'authCorpAccessToken', $temp['access_token'], $this->cacheTime);
                $authCorpAccessToken = cache($corpId . 'authCorpAccessToken');
            }else{
                check_exception($res['errmsg']?? '');
            }
        }
        return $authCorpAccessToken?? '';
    }

    /**
     * 获取SuiteAccessToken
     * @throws ValidateException
     * @return string
     */
    public function getSuiteAccessToken(): string
    {
        $suiteAccessToken = cache('suiteAccessToken');
        if(!$suiteAccessToken){
            $res = $this->curlFn($this->getSuiteAccessTokenUrl, [
                'suite_id' => $this->suiteId,
                'suite_secret' => $this->suiteSecret,
                'suite_ticket' => $this->getSuiteTicket()
            ]);
            if(isset($res['suite_access_token'])){
                cache('suiteAccessToken', $res['suite_access_token'], $this->cacheTime);
            }else{
                check_exception($res['errmsg']?? '');
            }
            $suiteAccessToken = cache('suiteAccessToken');
        }
        return $suiteAccessToken?? '';
    }

}